[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, isServer, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import { model as mongooseModel } from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { Comments } from '~/components/Comments';
  17. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  18. // import { useTranslation } from '~/i18n';
  19. import { PageContentFooter } from '~/components/PageContentFooter';
  20. import { RecentCreated } from '~/components/RecentCreated/RecentCreated';
  21. import { CrowiRequest } from '~/interfaces/crowi-request';
  22. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  23. // import { useIndentSize } from '~/stores/editor';
  24. // import { useRendererSettings } from '~/stores/renderer';
  25. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  26. import { EditorConfig } from '~/interfaces/editor-settings';
  27. import { CustomWindow } from '~/interfaces/global';
  28. import { RendererConfig } from '~/interfaces/services/renderer';
  29. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  30. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  31. import { PageModel, PageDocument } from '~/server/models/page';
  32. import { PageRedirectModel } from '~/server/models/page-redirect';
  33. import { UserUISettingsModel } from '~/server/models/user-ui-settings';
  34. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  35. import { useRedirectFrom } from '~/stores/page-redirect';
  36. import {
  37. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  38. } from '~/stores/ui';
  39. import loggerFactory from '~/utils/logger';
  40. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  41. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  42. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  43. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  44. import { BasicLayout } from '../components/Layout/BasicLayout';
  45. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  46. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  47. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  48. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  49. import {
  50. useCurrentUser, useCurrentPagePath,
  51. useIsLatestRevision,
  52. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  53. useIsEnabledStaleNotification, useIsIdenticalPath,
  54. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  55. useHackmdUri,
  56. useIsAclEnabled, useIsUserPage, useIsNotCreatable,
  57. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  58. useIsSlackConfigured, useIsBlinkedHeaderAtBoot, useRendererConfig, useEditingMarkdown,
  59. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage,
  60. } from '../stores/context';
  61. import {
  62. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  63. } from './utils/commons';
  64. // import { useCurrentPageSWR } from '../stores/page';
  65. const logger = loggerFactory('growi:pages:all');
  66. const {
  67. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage,
  68. } = pagePathUtils;
  69. const { removeHeadingSlash } = pathUtils;
  70. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  71. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  72. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  73. {
  74. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  75. return v?.data != null
  76. && v?.data.toObject != null
  77. && v?.meta != null
  78. && isIPageInfoForEntity(v.meta);
  79. },
  80. serialize: (v) => {
  81. return {
  82. data: superjson.stringify(v.data.toObject()),
  83. meta: superjson.stringify(v.meta),
  84. };
  85. },
  86. deserialize: (v) => {
  87. return {
  88. data: superjson.parse(v.data),
  89. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  90. };
  91. },
  92. },
  93. 'IPageToShowRevisionWithMetaTransformer',
  94. );
  95. const IdenticalPathPage = (): JSX.Element => {
  96. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  97. return <IdenticalPathPage />;
  98. };
  99. const PutbackPageModal = (): JSX.Element => {
  100. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  101. return <PutbackPageModal />;
  102. };
  103. type Props = CommonProps & {
  104. currentUser: IUser,
  105. pageWithMeta: IPageToShowRevisionWithMeta,
  106. // pageUser?: any,
  107. redirectFrom?: string;
  108. // shareLinkId?: string;
  109. isLatestRevision?: boolean
  110. isIdenticalPathPage?: boolean,
  111. isForbidden: boolean,
  112. isNotFound: boolean,
  113. IsNotCreatable: boolean,
  114. // isAbleToDeleteCompletely: boolean,
  115. isSearchServiceConfigured: boolean,
  116. isSearchServiceReachable: boolean,
  117. isSearchScopeChildrenAsDefault: boolean,
  118. isSlackConfigured: boolean,
  119. // isMailerSetup: boolean,
  120. isAclEnabled: boolean,
  121. // hasSlackConfig: boolean,
  122. // drawioUri: string,
  123. hackmdUri: string,
  124. // mathJax: string,
  125. // noCdn: string,
  126. // highlightJsStyle: string,
  127. isAllReplyShown: boolean,
  128. // isContainerFluid: boolean,
  129. editorConfig: EditorConfig,
  130. isEnabledStaleNotification: boolean,
  131. // isEnabledLinebreaks: boolean,
  132. // isEnabledLinebreaksInComments: boolean,
  133. // adminPreferredIndentSize: number,
  134. // isIndentSizeForced: boolean,
  135. disableLinkSharing: boolean,
  136. rendererConfig: RendererConfig,
  137. // UI
  138. userUISettings?: IUserUISettings
  139. // Sidebar
  140. sidebarConfig: ISidebarConfig,
  141. };
  142. const GrowiPage: NextPage<Props> = (props: Props) => {
  143. // const { t } = useTranslation();
  144. const router = useRouter();
  145. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  146. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  147. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  148. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  149. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  150. // register global EventEmitter
  151. if (isClient()) {
  152. (window as CustomWindow).globalEmitter = new EventEmitter();
  153. }
  154. // commons
  155. useEditorConfig(props.editorConfig);
  156. useCsrfToken(props.csrfToken);
  157. // UserUISettings
  158. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  159. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  160. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  161. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  162. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  163. // page
  164. useIsLatestRevision(props.isLatestRevision);
  165. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  166. useIsForbidden(props.isForbidden);
  167. useIsNotFound(props.isNotFound);
  168. useIsNotCreatable(props.IsNotCreatable);
  169. useRedirectFrom(props.redirectFrom);
  170. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  171. // useShared();
  172. // useShareLinkId(props.shareLinkId);
  173. useIsSharedUser(false); // this page cann't be routed for '/share'
  174. useIsIdenticalPath(false); // TODO: need to initialize from props
  175. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  176. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  177. useIsBlinkedHeaderAtBoot(false);
  178. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  179. useIsSearchServiceReachable(props.isSearchServiceReachable);
  180. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  181. useIsSlackConfigured(props.isSlackConfigured);
  182. // useIsMailerSetup(props.isMailerSetup);
  183. useIsAclEnabled(props.isAclEnabled);
  184. // useHasSlackConfig(props.hasSlackConfig);
  185. // useDrawioUri(props.drawioUri);
  186. useHackmdUri(props.hackmdUri);
  187. // useMathJax(props.mathJax);
  188. // useNoCdn(props.noCdn);
  189. // useIndentSize(props.adminPreferredIndentSize);
  190. useDisableLinkSharing(props.disableLinkSharing);
  191. useRendererConfig(props.rendererConfig);
  192. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  193. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  194. useIsAllReplyShown(props.isAllReplyShown);
  195. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  196. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  197. // const { data: editorMode } = useEditorMode();
  198. const { pageWithMeta, userUISettings } = props;
  199. let shouldRenderPutbackPageModal = false;
  200. if (pageWithMeta != null) {
  201. shouldRenderPutbackPageModal = _isTrashPage(pageWithMeta.data.path);
  202. }
  203. const pageId = pageWithMeta?.data._id;
  204. useCurrentPageId(pageId);
  205. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  206. useSWRxPageInfo(pageId, undefined, pageWithMeta?.meta); // store initial data
  207. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  208. useIsUserPage(isUserPage(pageWithMeta?.data.path ?? ''));
  209. useIsNotCreatable(props.isForbidden || !isCreatablePage(pageWithMeta?.data.path ?? '')); // TODO: need to include props.isIdentical
  210. useCurrentPagePath(pageWithMeta?.data.path);
  211. useCurrentPathname(props.currentPathname);
  212. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  213. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  214. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  215. // sync grant data
  216. useEffect(() => {
  217. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  218. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  219. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  220. useEffect(() => {
  221. const decodedURI = decodeURI(window.location.pathname);
  222. if (isClient() && decodedURI !== props.currentPathname) {
  223. router.replace(props.currentPathname, undefined, { shallow: true });
  224. }
  225. }, [props.currentPathname, router]);
  226. const classNames: string[] = [];
  227. // switch (editorMode) {
  228. // case EditorMode.Editor:
  229. // classNames.push('on-edit', 'builtin-editor');
  230. // break;
  231. // case EditorMode.HackMD:
  232. // classNames.push('on-edit', 'hackmd');
  233. // break;
  234. // }
  235. // if (page == null) {
  236. // classNames.push('not-found-page');
  237. // }
  238. return (
  239. <>
  240. <Head>
  241. {/*
  242. {renderScriptTagByName('drawio-viewer')}
  243. {renderScriptTagByName('mathjax')}
  244. {renderScriptTagByName('highlight-addons')}
  245. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  246. */}
  247. </Head>
  248. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  249. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={props.isContainerFluid}>
  250. <header className="py-0 position-relative">
  251. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  252. </header>
  253. <div className="d-edit-none">
  254. <GrowiSubNavigationSwitcher />
  255. </div>
  256. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  257. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  258. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  259. <div id="content-main" className="content-main grw-container-convertible">
  260. <div className="row">
  261. <div className="col">
  262. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  263. { !props.isIdenticalPathPage && (
  264. <>
  265. <PageAlerts />
  266. { props.isForbidden && <ForbiddenPage /> }
  267. { props.IsNotCreatable && <NotCreatablePage />}
  268. { !props.isForbidden && !props.IsNotCreatable && <DisplaySwitcher />}
  269. {/* <DisplaySwitcher /> */}
  270. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  271. {/* <PageStatusAlert /> */}
  272. </>
  273. ) }
  274. </div>
  275. </div>
  276. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  277. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  278. <div id="revision-toc-content" className="revision-toc-content"></div>
  279. </div>
  280. </div> */}
  281. </div>
  282. </div>
  283. {/* TODO: Check CSS import */}
  284. <footer className="footer d-edit-none">
  285. {/* TODO: Enable page_list.html */}
  286. {/* TODO: Enable isIdenticalPathPage or useIdenticalPath */}
  287. {/* { !props.isIdenticalPathPage && ( */}
  288. <Comments pageId={pageId} />
  289. {/* )} */}
  290. {/* TODO: Create UsersHomePageFooter conponent */}
  291. { !isUsersHomePage(props.currentPathname) && (
  292. <div className="container-lg user-page-footer py-5">
  293. <div className="grw-user-page-list-m d-edit-none">
  294. <h2 id="bookmarks-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  295. <i style={{ fontSize: '1.3em' }} className="fa fa-fw fa-bookmark-o"></i>
  296. Bookmarks
  297. </h2>
  298. <div id="user-bookmark-list" className="page-list">
  299. {/* TODO: No need page-list-container class ? */}
  300. <div className="page-list-container">
  301. {/* <BookmarkList userId={pageContainer.state.creator._id} /> */}
  302. </div>
  303. </div>
  304. </div>
  305. <div className="grw-user-page-list-m mt-5 d-edit-none">
  306. <h2 id="recently-created-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  307. <i id="recent-created-icon" className="mr-1">
  308. {/* <RecentlyCreatedIcon /> */}
  309. </i>
  310. Recently Created
  311. </h2>
  312. <div id="user-created-list" className="page-list">
  313. {/* TODO: No need page-list-container class ? */}
  314. <div className="page-list-container">
  315. {/* TODO: <RecentCreated userId={pageContainer.state.creator._id} /> */}
  316. <RecentCreated userId={pageWithMeta?.data.creator._id} />
  317. </div>
  318. </div>
  319. </div>
  320. </div>
  321. )}
  322. <PageContentFooter />
  323. </footer>
  324. <UnsavedAlertDialog />
  325. <DescendantsPageListModal />
  326. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  327. </BasicLayout>
  328. </>
  329. );
  330. };
  331. function getPageIdFromPathname(currentPathname: string): string | null {
  332. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  333. }
  334. class MultiplePagesHitsError extends ExtensibleCustomError {
  335. pagePath: string;
  336. constructor(pagePath: string) {
  337. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  338. this.pagePath = pagePath;
  339. }
  340. }
  341. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  342. const req: CrowiRequest = context.req as CrowiRequest;
  343. const { crowi } = req;
  344. const { revisionId } = req.query;
  345. const Page = crowi.model('Page') as PageModel;
  346. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  347. const { pageService } = crowi;
  348. let currentPathname = props.currentPathname;
  349. const pageId = getPageIdFromPathname(currentPathname);
  350. const isPermalink = _isPermalink(currentPathname);
  351. const { user } = req;
  352. if (!isPermalink) {
  353. // check redirects
  354. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  355. if (chains != null) {
  356. // overwrite currentPathname
  357. currentPathname = chains.end.toPath;
  358. props.currentPathname = currentPathname;
  359. // set redirectFrom
  360. props.redirectFrom = chains.start.fromPath;
  361. }
  362. // check whether the specified page path hits to multiple pages
  363. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  364. if (count > 1) {
  365. throw new MultiplePagesHitsError(currentPathname);
  366. }
  367. }
  368. const pageWithMeta: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  369. const page = pageWithMeta?.data as unknown as PageDocument;
  370. // populate & check if the revision is latest
  371. if (page != null) {
  372. page.initLatestRevisionField(revisionId);
  373. await page.populateDataToShowRevision();
  374. props.isLatestRevision = page.isLatestRevision();
  375. }
  376. props.pageWithMeta = pageWithMeta;
  377. }
  378. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  379. const req = context.req as CrowiRequest<IUserHasId & any>;
  380. const { user } = req;
  381. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  382. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  383. if (userUISettings != null) {
  384. props.userUISettings = userUISettings.toObject();
  385. }
  386. }
  387. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  388. const req: CrowiRequest = context.req as CrowiRequest;
  389. const { crowi } = req;
  390. const Page = crowi.model('Page') as PageModel;
  391. const { currentPathname } = props;
  392. const pageId = getPageIdFromPathname(currentPathname);
  393. const isPermalink = _isPermalink(currentPathname);
  394. const page = props.pageWithMeta?.data;
  395. if (props.isIdenticalPathPage) {
  396. // TBD
  397. }
  398. else if (page == null) {
  399. props.isNotFound = true;
  400. props.IsNotCreatable = !isCreatablePage(currentPathname);
  401. // check the page is forbidden or just does not exist.
  402. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  403. props.isForbidden = count > 0;
  404. }
  405. else {
  406. props.isNotFound = page.isEmpty;
  407. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  408. if (isPermalink && page.isEmpty) {
  409. props.currentPathname = page.path;
  410. }
  411. // /path/to/page ==> /62a88db47fed8b2d94f30000
  412. if (!isPermalink && !page.isEmpty) {
  413. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  414. if (!isToppage) {
  415. props.currentPathname = `/${page._id}`;
  416. }
  417. }
  418. }
  419. }
  420. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  421. // const req: CrowiRequest = context.req as CrowiRequest;
  422. // const { crowi } = req;
  423. // const UserModel = crowi.model('User');
  424. // if (isUserPage(props.currentPagePath)) {
  425. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  426. // if (user != null) {
  427. // props.pageUser = JSON.stringify(user.toObject());
  428. // }
  429. // }
  430. // }
  431. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  432. const req: CrowiRequest = context.req as CrowiRequest;
  433. const { crowi } = req;
  434. const {
  435. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  436. } = crowi;
  437. props.isSearchServiceConfigured = searchService.isConfigured;
  438. props.isSearchServiceReachable = searchService.isReachable;
  439. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  440. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  441. // props.isMailerSetup = mailService.isMailerSetup;
  442. props.isAclEnabled = aclService.isAclEnabled();
  443. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  444. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  445. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  446. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  447. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  448. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  449. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  450. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  451. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  452. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  453. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  454. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  455. props.editorConfig = {
  456. upload: {
  457. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  458. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  459. },
  460. };
  461. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  462. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  463. props.rendererConfig = {
  464. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  465. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  466. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  467. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  468. plantumlUri: process.env.PLANTUML_URI ?? null,
  469. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  470. // XSS Options
  471. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  472. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  473. tagWhiteList: crowi.xssService.getTagWhiteList(),
  474. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  475. };
  476. props.sidebarConfig = {
  477. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  478. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  479. };
  480. }
  481. /**
  482. * for Server Side Translations
  483. * @param context
  484. * @param props
  485. * @param namespacesRequired
  486. */
  487. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  488. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  489. props._nextI18Next = nextI18NextConfig._nextI18Next;
  490. }
  491. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  492. const req = context.req as CrowiRequest<IUserHasId & any>;
  493. const { user } = req;
  494. const result = await getServerSideCommonProps(context);
  495. // check for presence
  496. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  497. if (!('props' in result)) {
  498. throw new Error('invalid getSSP result');
  499. }
  500. const props: Props = result.props as Props;
  501. if (user != null) {
  502. props.currentUser = user.toObject();
  503. }
  504. try {
  505. await injectPageData(context, props);
  506. }
  507. catch (err) {
  508. if (err instanceof MultiplePagesHitsError) {
  509. props.isIdenticalPathPage = true;
  510. }
  511. else {
  512. throw err;
  513. }
  514. }
  515. await injectUserUISettings(context, props);
  516. await injectRoutingInformation(context, props);
  517. injectServerConfigurations(context, props);
  518. await injectNextI18NextConfigurations(context, props, ['translation']);
  519. return {
  520. props,
  521. };
  522. };
  523. export default GrowiPage;